package cn.zhxu.toys.msg;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @since 0.5.6
 * @author Zhou.xu
 *
 * 带有模板的短信发送器
 */
public abstract class AbstractMsgSender implements MsgSender {

	protected final Logger log = LoggerFactory.getLogger(getClass());

	/** 发送器名称 */
	private String name;

	/** 消息模板 */
	private List<MsgTemplate> templates;

	public AbstractMsgSender() {
	}

	public AbstractMsgSender(String name) {
		this.name = name;
	}

	/**
	 * 初始化 发送器
	 * @param params 参数
	 */
	public abstract void init(Map<String, String> params) throws MsgSenderInitException;

	public static class MsgSenderInitException extends RuntimeException {

		public MsgSenderInitException(String message) {
			super(message);
		}

		public MsgSenderInitException(String message, Throwable cause) {
			super(message, cause);
		}

	}

	@Override
	public String name() {
		return name;
	}

	@Override
	public SendResult send(String phone, String tmplName, String... tmplArgs) {
		MsgTemplate template = getMsgTemplate(tmplName);
		if (template == null) {
			throw new RuntimeException("No such MsgTemplate named: " + tmplName);
		}
		return send(phone, template, tmplArgs);
	}

	public abstract SendResult send(String phone, MsgTemplate template, String... tmplArgs);

	public MsgTemplate getMsgTemplate(String tmplName) {
		if (tmplName != null && templates != null) {
			for (MsgTemplate template: templates) {
				if (tmplName.equals(template.getName())) {
					return template;
				}
			}
		}
		return null;
	}
	
	public synchronized void addMsgTemplate(MsgTemplate template) {
		if (templates == null) {
			templates = new ArrayList<>();
		}
		templates.add(template);
	}

	public synchronized void setTemplates(List<MsgTemplate> templates) {
		this.templates = templates;
	}

	public List<MsgTemplate> getTemplates() {
		return templates;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}
